package com.ssy.lingxi.platform.manage.serviceimpl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ssy.lingxi.common.constant.CommonConstant;
import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.common.model.vo.PageVO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.component.redis.service.IRedisStringUtils;
import com.ssy.lingxi.platform.manage.constant.CommonBooleanEnum;
import com.ssy.lingxi.platform.manage.entity.base.ShopRule;
import com.ssy.lingxi.platform.manage.entity.base.ShopRuleDetail;
import com.ssy.lingxi.platform.manage.model.request.shop.ShopRuleDetailRequest;
import com.ssy.lingxi.platform.manage.model.request.shop.ShopRuleRequest;
import com.ssy.lingxi.platform.manage.repository.ShopRuleDetailRepository;
import com.ssy.lingxi.platform.manage.repository.ShopRuleRepository;
import com.ssy.lingxi.platform.manage.service.IShopRuleService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wyx
 * @version 2.0.0
 * @menu 平台后台-系统管理-商城规则配置
 * @date 2021-09-26
 */
@Service
public class ShopRuleServiceImpl implements IShopRuleService {

    @Resource
    private ShopRuleRepository shopRuleRepository;
    @Resource
    private ShopRuleDetailRepository shopRuleDetailRepository;
    @Resource
    private IRedisStringUtils redisStringUtils;

    /**
     * 商城规则配置列表
     *
     * @param pageVO     分页实体
     * @param memberName 会员名称
     */
    @Override
    public Wrapper<PageData<ShopRule>> list(PageVO pageVO, String memberName) {
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("memberId"));

        Page<ShopRule> all = shopRuleRepository.findAll((root, query, cb) -> {
            List<Predicate> predicateList = new ArrayList<>();
            if (StrUtil.isNotBlank(memberName)) {
                predicateList.add(cb.like(root.get("memberName"), "%" + memberName + "%"));
            }
            Predicate[] p = new Predicate[predicateList.size()];
            return query.where(predicateList.toArray(p)).getRestriction();
        }, page);
        return Wrapper.success(new PageData<>(all.getTotalElements(), all.getContent()));
    }

    /**
     * 获取商城规则配置信息
     *
     * @param id 商城规则id
     */
    @Override
    public Wrapper<ShopRule> get(Long id) {
        ShopRule shopRule = shopRuleRepository.findById(id).orElse(null);
        return Wrapper.success(shopRule);
    }

    /**
     * 新增商城规则配置
     *
     * @param shopRuleRequest 请求实体
     */
    @Override
    public Wrapper<Void> add(ShopRuleRequest shopRuleRequest) {
        int count = shopRuleRepository.countByMemberId(shopRuleRequest.getMemberId());
        if (count > 0) {
            return Wrapper.fail(ResponseCode.PLATFORM_MANAGE_MEMBER_SHOP_RULE_EXIST);
        }
        ShopRule shopRule = new ShopRule();
        BeanUtils.copyProperties(shopRuleRequest, shopRule);

        List<ShopRuleDetail> detailList = new ArrayList<>();
        for (ShopRuleDetailRequest shopRuleDetailRequest : shopRuleRequest.getShopList()) {
            ShopRuleDetail detail = new ShopRuleDetail();
            BeanUtils.copyProperties(shopRuleDetailRequest, detail);
            detail.setId(null);
            detail.setShopRule(shopRule);
            detailList.add(detail);
        }
        shopRule.setStatus(CommonBooleanEnum.YES.getCode());
        shopRule.setShopList(detailList);
        shopRuleRepository.save(shopRule);
        initToRedis();
        return Wrapper.success();
    }

    /**
     * 修改商城规则配置
     *
     * @param shopRuleRequest 请求实体
     */
    @Override
    public Wrapper<Void> update(ShopRuleRequest shopRuleRequest) {
        ShopRule shopRule = shopRuleRepository.findById(shopRuleRequest.getId()).orElse(null);
        if (shopRule == null) {
            return Wrapper.fail(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }
        BeanUtils.copyProperties(shopRuleRequest, shopRule);

        List<ShopRuleDetail> detailList = new ArrayList<>();
        for (ShopRuleDetailRequest shopRuleDetailRequest : shopRuleRequest.getShopList()) {
            ShopRuleDetail detail = new ShopRuleDetail();
            BeanUtils.copyProperties(shopRuleDetailRequest, detail);
            detail.setShopRule(shopRule);
            detailList.add(detail);
        }
        //商城明细
        shopRule.setShopList(detailList);
        shopRuleRepository.save(shopRule);
        initToRedis();
        return Wrapper.success();
    }

    /**
     * 启用/停用商城规则配置
     *
     * @param id     商城规则id
     * @param status 状态 0-无效 1-有效
     */
    @Override
    public Wrapper<Void> updateStatus(Long id, Integer status) {
        ShopRule shopRule = shopRuleRepository.findById(id).orElse(null);
        if (shopRule == null) {
            return Wrapper.fail(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }
        shopRule.setStatus(status);
        shopRuleRepository.save(shopRule);
        initToRedis();
        return Wrapper.success();
    }

    /**
     * 删除商城规则配置
     *
     * @param id 商城规则id
     */
    @Override
    public Wrapper<Void> delete(Long id) {
        ShopRule shopRule = shopRuleRepository.findById(id).orElse(null);
        if (shopRule == null) {
            return Wrapper.fail(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }
        shopRuleRepository.delete(shopRule);
        initToRedis();
        return Wrapper.success();
    }

    /**
     * 初始化到redis
     */
    @Override
    public void initToRedis() {
        //先清除缓存
        redisStringUtils.delByPrex(Constants.REDIS_KEY_SELF_SHOP, Constants.REDIS_PLATFORM_MANAGE_INDEX);
        List<ShopRule> shopRuleList = shopRuleRepository.findByStatus(CommonConstant.State.STATE_START);
        if (shopRuleList != null && !shopRuleList.isEmpty()) {
            HashMap<String, Map<String, String>> keyValueMap = new HashMap<>();
            shopRuleList.forEach(shopRule -> {
                Long memberId = shopRule.getMemberId();
                Long memberRoleId = shopRule.getMemberRoleId();
                List<ShopRuleDetail> shopList = shopRule.getShopList();
                Map<String, String> map = new HashMap<>();
                List<ShopRuleDetail> shopRuleDetailList = shopList.stream().filter(shop -> shop.getState().equals(CommonConstant.State.STATE_START)).collect(Collectors.toList());
                if (shopRuleDetailList.size() > 0) {
                    shopRuleDetailList.forEach(shop -> {
                        shop.setShopRule(null);
                        map.put(String.valueOf(shop.getId()), JSONUtil.toJsonStr(shop));
                    });
                    keyValueMap.put(Constants.REDIS_KEY_SELF_SHOP + "_" + memberId + "_" + memberRoleId, map);
                }
            });
            if (keyValueMap.size() > 0) {
                redisStringUtils.hMSetBatch(keyValueMap, Constants.REDIS_PLATFORM_MANAGE_INDEX);
            }
        }
    }
}
